﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using Microsoft.Win32.TaskScheduler;

namespace TSMonitor.Core
{
	public class TaskObservable : IObservable<IList<TaskInfo>>
	{
		private readonly IObservable<IList<TaskInfo>> _tasksObservable;

		public TaskObservable(IEnumerable<ServerInfo> servers, TimeSpan period)
		{
			_tasksObservable = Observable
				.Timer(TimeSpan.FromSeconds(0), period)
				// TODO: get tasks asynchroniously
				.Select(x => servers.SelectMany(GetTaskInfos).ToList());
		}

		private static IList<TaskInfo> GetTaskInfos(ServerInfo serverInfo)
		{
			using (var taskService = new TaskService(serverInfo.TargetServer))
			{
				return taskService.RootFolder.GetTasks()
					.Select(t => new TaskInfo
					             	{
					             		Name = t.Name,
					             		State = t.State,
					             		LastRunTime = t.LastRunTime,
					             		LastTaskResult = t.LastTaskResult,
					             		Enabled = t.Enabled,
										ServerInfo = serverInfo,
										Path = t.Path
					             	})
					.ToList();
			}
		}

		public IDisposable Subscribe(IObserver<IList<TaskInfo>> observer)
		{
			return _tasksObservable.Subscribe(observer);
		}
	}
}